const http = require('http')
const querysting = require('querystring') // qs
const path = require('path')
const { ocrManage } = require('./index')

// nodejs中如何处理post参数

const postData = (req) => {
	let str = ''
	return new Promise((resolve, reject) => {
		req.on('data', (chunk) => {
			str += chunk
		})
		req.on('end', (chunk) => {
			console.log('str', JSON.parse(str))
			resolve(JSON.parse(str))
		})
	})
}

const server = http.createServer(async (req, res) => {
	const method = req.method
	const url = req.url.split('?')
	const pathName = url[0]
	const query = url[1]

	// 文字是识别接口 1. 接收前端传递的base64图片数据，2. 调用后台ocr接口
	if (pathName === '/api/ocr' && method === 'POST') {
		res.setHeader('Content-Type', 'text/plain;charset=utf-8')
		res.setHeader('Access-Control-Allow-Origin', '*')
		res.setHeader(
			'Access-Control-Allow-Methods',
			'POST, GET, PUT, OPTIONS, DELETE'
		)
		const result = await postData(req)
		console.log('ocrManage:', ocrManage)
		// ocr识别接口
		const ocrText = await ocrManage.accurateBasic(result.file)
		res.end(
			JSON.stringify({
				code: 0,
				msg: 'success',
				data: { result, ocrText }
			})
		)
		return
	}

	if (pathName === '/api/test' && method === 'GET') {
		res.setHeader('Content-Type', 'text/plain;charset=utf-8')
		res.setHeader('Access-Control-Allow-Origin', '*')
		res.setHeader('Access-Control-Allow-Methods', 'GET,POST')
		res.end(
			JSON.stringify({
				code: 0,
				msg: '测试get接口'
			})
		)
		return
	}

	res.end(
		JSON.stringify({
			pathName,
			query
		})
	)
})

server.listen(8888, () => {
	console.log('server port is 8888')
})
